<template>
    <div>
        <!--查询条件start --111s-->
        <el-form :inline="true" :model="query" class="query-form" size="small">
            <el-form-item>
                <el-button type="primary" icon="el-icon-edit" @click.native="showDialogAddOrEdit(null,null)">添加
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-date-picker
                    v-model="createTime"
                    type="datetimerange"
                    :picker-options="pickerOptions"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    align="left"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :default-time="['00:00:00','23:59:59']"
                    @change="dateChange"
                ></el-date-picker>
            </el-form-item>
            <el-form-item class="query-form-item">
                <el-input
                    v-model="query.content"
                    placeholder="请输入用户名"
                    prefix-icon="el-icon-search"
                    @keyup.enter.native="onSubmit"
                    clearable
                ></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-refresh" @click="onRest"></el-button>
                <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>

            </el-form-item>
            <el-form-item style="right: 10px;position: absolute;">
                <el-button type="primary" icon="el-icon-edit" @click.native="showmseeage()">站内信
                </el-button>
            </el-form-item>
        </el-form>
        <!--查询条件end-->

        <!--列表start --222s-->
        <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="list"
            :header-cell-style="{background:'#F4F4F5',color:'#606266'}"
            @selection-change="handleSelectionChange"
            border
        >
            <el-table-column type="selection" width="50" fixed/>
            <el-table-column label="用户 ID" prop="userid" width="80" align="center"/>

            <el-table-column label="头像" prop="userpic" align="center" width="200">
                <template slot-scope="scope">
                    <el-popover v-if="scope.row.userpic" placement="right" trigger="hover">
                        <img :src="scope.row.userpic" style="width:400px;border-radius:3px;">
                        <img
                            slot="reference"
                            :src="scope.row.userpic"
                            style="max-height: 80px;max-width: 50px;border-radius:5px;"
                        >
                    </el-popover>
                    <span v-else>-</span>
                </template>
            </el-table-column>


            <el-table-column label="用户昵称" prop="usernick" align="center"/>

            <el-table-column label="手机号码" prop="usermobile" align="center"/>

            <el-table-column label="禁止登录" prop="userban" align="center" width="120">
                <template slot-scope="scope">
                    <span>{{ scope.row.userban==0?'允许登录':'禁止登录'}}    </span>
                    <el-switch
                        v-model="scope.row.userban"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        active-value="0"
                        inactive-value="1"
                        @change="swithchange(scope.row)"
                    >
                    </el-switch>
                </template>

            </el-table-column>

            <el-table-column label="添加时间" with="300" :show-overflow-tooltip="true" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-time" v-if="scope.row.userregisttime!=null"></i>
                    <span
                        v-if="scope.row.userregisttime!=null"
                    >{{ scope.row.userregisttime | formatDateStr('yyyy-MM-dd hh:mm:ss') }}</span>
                    <span v-else>无</span>
                </template>
            </el-table-column>
            <el-table-column label="等级" prop="onshelfstatus" align="center" width="120">
                <template slot-scope="scope">
                    <span v-if="scope.row.uservip==1">VIP1</span>
                    <span v-else-if="scope.row.uservip==2">VIP2</span>
                    <span v-else-if="scope.row.uservip==3">VIP3</span>
                    <span v-else-if="scope.row.uservip==4">VIP4</span>
                </template>
            </el-table-column>
            <el-table-column label="商城品牌等级" prop="onshelfstatus" align="center" width="120">
                <template slot-scope="scope">
                    <span v-if="scope.row.userentitytype==0">-</span>
                    <span v-else-if="scope.row.userentitytype==1">初级商城</span>
                    <span v-else-if="scope.row.userentitytype==2">高级商城</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="320">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini"  @click.native="setUpForm(scope.$index, scope.row)" >设置商城品牌等级</el-button>
                    <el-button type="primary" size="mini"  @click.native="detailForm(scope.$index, scope.row)" >查看 </el-button>
                    <el-button type="danger"  size="mini"  @click.native="handleDel(scope.row.userid)"  >删除 </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--列表end --222e-->

        <!--全选删除start-->
        <div class="left-container">
            <el-button type="danger" size="small" @click="delGroup()">删除已选</el-button>
            <transition name="el-fade-in-linear">
                <el-button size="small" @click="toggleSelection()" v-show="cancelToggle">取消选择</el-button>
            </transition>
        </div>
        <!--全选删除end-->

        <!--分页模块start-->
        <el-pagination
            class="pagination-container"
            background
            :page-size="query.pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="total,sizes,prev, pager, next, jumper"
            :current-page="query.currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :total="totalNumber"
        ></el-pagination>
        <!--分页模块end-->

        <!--新增/编辑弹框start--333s-->
        <el-dialog
            :title="dialogAddOrEditName"
            :visible.sync="dialogAddOrEdit"
            width="30%"
            :before-close="hideDialogAddOrEdit">
            <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户昵称" prop="usernick">
                    <el-input v-model="formData.usernick"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="usermobile">
                    <el-input v-model="formData.usermobile"></el-input>
                </el-form-item>
                <el-form-item label="登录密码" prop="userpassword">
                    <el-input v-model="formData.userpassword"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogAddOrEdit = false">取 消</el-button>
            <el-button type="primary" :loading="formSumbitLoding" @click="formSumbit">提交</el-button>
          </span>
        </el-dialog>


        <!--查看弹框-->
        <el-dialog
            :title="formMap[formName]"
            :visible.sync="detailVisible"
            :before-close="hideDetailForm"
            width="700px"
            top="5vh"
            v-dialogDrag
        >
            <el-form :model="formData" label-width="140px">


                <el-form-item style="border-bottom:1px solid #ebeef5;" label-width="0px">
                    <el-form-item label="头像：" style="width:30%;display: inline-block">
                        <!--<img :src="formData.userpic" alt style="width: 60px;height: 50px">-->
                        <el-popover v-if="formData.userpic" placement="right" trigger="hover">
                            <img :src="formData.userpic" style="width:400px;border-radius:3px;">
                            <img
                                slot="reference"
                                :src="formData.userpic"
                                style="max-height: 80px;max-width: 50px;border-radius:5px;"
                            >
                        </el-popover>
                        <span v-else>-</span>

                    </el-form-item>
                    <el-form-item label="昵称：" style="margin-left:80px;width:30%;display: inline-block;">
                        <input v-model="formData.usernick" type="text" readonly>
                    </el-form-item>
                </el-form-item>

                <el-form-item style="border-bottom:1px solid #ebeef5;" label-width="0px">

                    <el-form-item label="性别：" style="width:30%;display: inline-block;">
                        <template>
                            <div v-if="formData.usersex===1">
                                <span>男</span>
                            </div>
                            <div v-else-if="formData.usersex===2">
                                <span>女</span>
                            </div>
                            <div v-else >
                                <span>未知</span>
                            </div>
                        </template>


                        <!--  <input v-model="formData.usersex" type="text" readonly>-->
                    </el-form-item>
                    <el-form-item label="手机号：" style="margin-left:80px; width:30%;display: inline-block;">
                        <input v-model="formData.usermobile" type="text" readonly>
                    </el-form-item>

                </el-form-item>

                <el-form-item style="border-bottom:1px solid #ebeef5;" label-width="0px">
                    <el-form-item label="优惠券：" style="width:30%;display: inline-block;">
                        <input v-model="formData.busdiscount" type="text" readonly>
                    </el-form-item>
                    <el-form-item label="注册时间：" style="margin-left:80px; width:30%;display: inline-block;">
                        <input
                            :value="formData.userregisttime |formatDateStr('yyyy-MM-dd') "
                            type="text"
                            readonly
                        >
                    </el-form-item>
                </el-form-item>

                <el-form-item style="border-bottom:1px solid #ebeef5;" label-width="0px">

                    <el-form-item label="积分：" style="width:30%;display: inline-block;">
                        <input v-model="formData.usertotalintegral" type="text" readonly>
                    </el-form-item>
                    <el-form-item label="收藏：" style="margin-left:80px; width:30%;display: inline-block;">
                        <input v-model="formData.usercount" type="text" readonly>
                    </el-form-item>

                </el-form-item>

                <el-form-item style="border-bottom:1px solid #ebeef5;" label-width="0px">

                    <el-form-item label="分销等级：" style="width:30%;display: inline-block;">
                        <!--  <input v-model="formData.userid" type="text" readonly>-->
                        <span>{{formData.usersuperiorid==null?'一级':'二级'}}</span>
                    </el-form-item>
                    <el-form-item label="用户订单：" style="margin-left:80px; width:30%;display: inline-block;">
                        <input v-model="formData.countouder" type="text" readonly @click="tomyorder(formData.userid)">
                    </el-form-item>

                </el-form-item>

                <el-form-item style="border-bottom:1px solid #ebeef5;" label-width="0px">
                    <!--列表start --222s-->
                    <el-table
                        ref="multipleTable"
                        v-loading="loading"
                        :data="formData.addresslist"
                        :header-cell-style="{background:'#F4F4F5',color:'#606266'}"
                        border
                    >
                        <el-table-column label="收货地址" prop="useraddress" align="center">
                        </el-table-column>
                        <el-table-column label="默认地址" width="100">
                            <template slot-scope="scope">
                                <span>{{ scope.row.useraddressdefault==0?'否':'是'}}</span>
                            </template>
                        </el-table-column>


                    </el-table>

                </el-form-item>

                <el-form-item style="border-bottom:1px solid #ebeef5;color: #9E9E9E" label="分销团队">

                </el-form-item>

                <el-form-item style="border-bottom:1px solid #ebeef5;" label-width="0px">

                    <el-form-item label="好友数量：" style="width:30%;display: inline-block;">
                        <input v-model="formData.countfriend" type="text" readonly @click="tomyfriend(formData.userid)">

                    </el-form-item>
                    <el-form-item label="好友订单：" style="margin-left:80px; width:30%;display: inline-block;">
                        <input v-model="formData.countfriendouder" type="text" readonly
                               @click="tofriendorder(formData.userid)">
                    </el-form-item>

                </el-form-item>
                <el-form-item style="border-bottom:1px solid #ebeef5;" label-width="0px">

                    <el-form-item label="发票:" >
                     <!--   <span>{{formData.invoicelist}}</span>-->

                            <ul>
                                <li>
                                    <div v-for="(item,index) in formData.invoicelist" :key="index">
                                        <span style="color: black">发票信息{{index}}</span>
                                        <span style="margin-left: 20px;color: black">{{item.invoicetype==0?'普通':'专用'}}</span>
                                        <span style="margin-left: 20px;color: black">{{item.rrisetype==0?'个人':'单位'}}</span>
                                        <span style="margin-left: 20px;color: black">{{item.invoicerrise}}</span>
                                    </div>
                                </li>
                            </ul>

                    </el-form-item>


                </el-form-item>


            </el-form>
        </el-dialog>
        <!--查看弹框-->
        <el-dialog
            :title="formMap[formName]"
            :visible.sync="setupVisible"
            :before-close="hideSetupForm"
            width="700px"
            top="5vh"
            v-dialogDrag
        >
            <el-form :model="formData" label-width="140px">
                <el-form-item label="商城品牌:" prop="warehousearea"  style="width:50%;display: inline-block;margin-left: 20px">
                    <el-select v-model="formData.userentitytype" label="区" placeholder="请选择商城品牌"   clearable>
                        <el-option label="普通用户" value="0">  </el-option>
                        <el-option label="初级商城" value="1">  </el-option>
                        <el-option label="高级商城" value="2">  </el-option>
                    </el-select>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">

                <el-button @click.native="hideSetupForm()">取消</el-button>
                <el-button type="primary" @click.native="setupFormSubmit()" :loading="formLoading">提交</el-button>
            </div>
        </el-dialog>

    </div>
</template>
<script>
    import {getList, addUser, updateUser, delUser,setupUser} from "../../api/mbuser/mbuser";

    /*用作表单的数据初始化*/
    const formJson = {
        addresslist: [],
        busdiscount: "",
        countfriend: "",
        countfriendouder: "",
        countouder: "",
        distributionGrade: "",
        easemobid: "",
        easemobuuid: "",
        infotips: "",
        invoicelist: [],
        isnew: "",
        userban: "",
        usercount: "",
        usercurrentlogintime: "",
        userdel: "",
        usergrade: "",
        userid: "",
        userip: "",
        usermobile: "",
        usernick: "",
        userpassword: "",
        userpic: "",
        userregisttime: "",
        usersex: "",
        usersuperiorid: "",
        usersurplusintegral: "",
        usertotalintegral: "",
        userentitytype: "0"

    };

    export default {
        data() {
            var checkPhone = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error("手机号不能为空"));
                } else {
                    const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
                    console.log(reg.test(value));
                    if (reg.test(value)) {
                        callback();
                    } else {
                        return callback(new Error("请输入正确的手机号"));
                    }
                }
            };

            return {
                pickerOptions: {//快速选择日期
                    shortcuts: [
                        {
                            text: "最近一周",
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(
                                    start.getTime() - 3600 * 1000 * 24 * 7
                                );
                                picker.$emit("pick", [start, end]);
                            }
                        },
                        {
                            text: "最近一个月",
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(
                                    start.getTime() - 3600 * 1000 * 24 * 30
                                );
                                picker.$emit("pick", [start, end]);
                            }
                        },
                        {
                            text: "最近三个月",
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(
                                    start.getTime() - 3600 * 1000 * 24 * 90
                                );
                                picker.$emit("pick", [start, end]);
                            }
                        },
                        {
                            text: "最近六个月",
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(
                                    start.getTime() - 3600 * 1000 * 24 * 180
                                );
                                picker.$emit("pick", [start, end]);
                            }
                        }
                    ]
                },
                query: {//查询条件
                    content: "",
                    startTime: "",
                    endTime: "",
                    currentPage: 1,
                    pageSize: 10,
                },
                detailVisible: false,
                setupVisible: false,
                formName: null,
                formMap: {
                    add: "添加",
                    edit: "编辑",
                    detail: "详情",
                    setup: "商城品牌设置"
                },
                createTime: [],//选择日期时需要的model
                list: [],//列表集合
                totalNumber: 0,//分页总页数
                loading: true,//列表加载
                allLoding: false,//全屏加载
                formSumbitLoding: false,//表单提交加载
                formLoading: false,//表单提交加载
                cancelToggle: false,//列表是否全选
                multipleSelection: [], //多选集合
                dialogAddOrEdit: false,//新增或编辑弹框开关
                dialogAddOrEditName: "",//新增或编辑弹框名字
                formData: formJson,//新增或修改的对象

                rules: {//表单校验

                    usernick: {
                        required: true,
                        message: "请输入真实姓名",
                        trigger: "blur"
                    },
                    usermobile: {
                        required: true,
                        validator: checkPhone,
                        message: "请输入手机号",
                        trigger: "blur"
                    },
                    userpassword: {
                        required: true,
                        message: "请输入密码",
                        trigger: "blur"
                    }


                }
            };
        },
        methods: {
            //我的好友
            tomyuser(uid) {
                if (uid !== undefined) {
                    // alert("=="+uid);
                    this.$router.push({path: '/mbUser/myfriend', query: {uid: uid}})
                }

            },
            //h好友的好友
            tomyfriend(uid) {
                if (uid !== undefined) {
                    // alert("=="+uid);
                    this.$router.push({path: '/mbUser/myfriend', query: {uid: uid}})
                }

            },
            //我的订单
            tomyorder(uid) {

                if (uid !== undefined) {
                    //  alert("=="+uid);
                    this.$router.push({path: '/mbUser/myorder', query: {uid: uid,flag:"0"}})
                }
            },
            //好友订单
            tofriendorder(uid) {
                if (uid !== undefined) {
                    //  alert("=="+uid);
                    this.$router.push({path: '/mbUser/myorder', query: {gid: uid,flag:"1"}})
                }
            },



            //跳转到站内信
            showmseeage() {
                this.$router.push({path: '/mbUser/sysMsg'})
            },
            /*获取列表事件*/
            getList() {
                this.loading = true;
                getList(this.query).then(response => {
                    if (response.code != 0) {
                        this.$message.error(response.message);
                        return false;
                    }

                    this.list = response.data.list || [];
                    if (this.list.length > 0) {
                        let mylist = this.list
                        for (var i = 0; i < mylist.length; i++) {
                            mylist[i].userban = mylist[i].userban.toString();
                        }
                        this.list = mylist
                    }

                    this.totalNumber = response.data.totalNumber || 0;
                    setTimeout(() => {
                        this.loading = false;
                    }, 0.3 * 1000);
                }).catch(() => {
                    this.loading = false;
                    this.list = [];
                })
            },
            setupFormSubmit(){
                this.formLoading = true;
                let data={
                    userid:this.formData.userid,
                    userentitytype:this.formData.userentitytype,
                }
                var params = new URLSearchParams(data);
                setupUser(params).then(response => {
                    this.formLoading = false;
                    if (response.code != 0) {
                        this.$message.error(response.message);
                        this.formLoading = false;
                        return false;
                    }
                    this.$message.success("操作成功");

                    this.formLoading = false;
                    this.setupVisible = false;
                    // 加载表格数据
                    this.getList();
                    // 清空表单
                    // this.$refs["dataForm"].resetFields();

                });
            },
            /*新增或者编辑提交事件*/
            formSumbit() {
                //表单校验通过
                this.$refs["ruleForm"].validate(valid => {
                    if (valid) {
                        this.formSumbitLoding = true;
                        var params = new URLSearchParams(this.formData);
                        addUser(params).then(response => {
                            this.formLoading = false;
                            if (response.code != 0) {
                                this.$message.error(response.message);
                                this.formSumbitLoding = false;
                                return false;
                            }
                            this.$message.success("操作成功");

                            this.formSumbitLoding = false;
                            this.dialogAddOrEdit = false;
                            // 加载表格数据
                            this.getList();
                            // 清空表单
                            this.$refs["dataForm"].resetFields();

                        });

                    }
                });
                //new URLSearchParams(this.query)  提交数据格式不正确时可以转一下
            },

            /*列表查询条件事件*/
            onSubmit() {
                this.query.currentPage = 1;
                this.$router.push({
                    path: "",
                    query: this.query
                });
                this.getList();
            },

            /*刷新*/
            onRest() {
                this.$router.push({
                    path: ""
                });
                //刷新事件需要重置查询条件
                this.createTime = [];
                this.query = {
                    currentPage: 1,
                    pageSize: 10,
                };
                this.getList();
            },
            //开关禁止登陆
            swithchange(row) {
                if (row !== null) {
                    var params = new URLSearchParams();
                    params.append("userid", row.userid)
                    params.append("userban", row.userban)
                    updateUser(params).then(response => {
                        this.formLoading = false;
                        if (response.code != 0) {
                            this.$message.error(response.message);
                            return false;
                        }
                        this.$message.success("操作成功");
                    });
                }
            },

            setUpForm(index, row) {
                if (row !== null) {
                    this.setupVisible = true;
                    this.formData = Object.assign({}, row);
                    this.formData.userentitytype = row.userentitytype+"";
                    this.formName = "setup";
                }
            },

            //显示 查看弹框
            detailForm(index, row) {
                if (row !== null) {
                    this.detailVisible = true;
                    this.formData = Object.assign({}, row);
                    this.formName = "detail";
                }
            },
            // 隐藏详情弹框
            hideDetailForm() {
                // 更改值
                this.detailVisible = !this.detailVisible;
                return true;
            },            // 隐藏详情弹框
            hideSetupForm() {
                // 更改值
                this.setupVisible = !this.setupVisible;
                return true;
            },
            /*显示 -新增或者编辑弹框*/
            showDialogAddOrEdit(index, row) {
                this.dialogAddOrEdit = true;
                this.formData = Object.assign({}, formJson);//将弹框内表单内容初始化
                if (row !== null) {
                    //如果row不为空，说明是修改，因为row是修改时携带过来此列的所有信息
                    this.formData = Object.assign({}, row);//修改则将列内容深拷贝到表单内容中
                    this.dialogAddOrEditName = "编辑";
                } else {
                    this.dialogAddOrEditName = "新增";
                }
            },

            /*隐藏 -新增或编辑弹框*/
            hideDialogAddOrEdit() {
                this.dialogAddOrEdit = false;

                //隐藏弹框时需要清除弹框内容
                if (this.$refs["ruleForm"]) {
                    this.$refs['ruleForm'].resetFields();//清除formData表单
                    this.$refs["ruleForm"].clearValidate();//清除表单验证
                }
                //如果上传文件，还需要清除文件列表
            },

            /*点击页数*/
            handleCurrentChange(val) {
                this.query.currentPage = val;
                this.getList();
            },

            /*选择每页条数【10,20,30,40,50】*/
            handleSizeChange(val) {
                this.query.pageSize = val;
                this.getList();
            },

            /*取消全选事件*/
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row);
                    });
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },

            /*列表复选框选择事件*/
            handleSelectionChange(val) {
                this.multipleSelection = val;
                if (val == "") {
                    this.cancelToggle = false;
                    return;
                }
                this.cancelToggle = true;
            },

            /*全选删除事件*/
            delGroup() {
                console.log(this.multipleSelection)
                var ids = this.multipleSelection.map(item => item.userid).join(); //获取所有选中行的id组成的字符串，以逗号分隔
                if (ids == "") {
                    this.$message({
                        message: "请先选择",
                        type: "warning"
                    });
                    return;
                }
                this.handleDel(ids);
            },

            /*单击删除事件*/
            handleDel(ids) {
                if (ids) {
                    this.$confirm("确认要删除吗?", "提示", {
                        type: "warning"
                    })
                        .then(() => {

                            this.loading = true;
                            var params = new URLSearchParams();
                            params.append("ids", ids);
                            delUser(params)
                                .then(response => {
                                    this.loading = false;
                                    if (response.code) {
                                        this.$message.error(response.message);
                                        return false;
                                    }
                                    this.$message.success("删除成功");
                                    // 刷新数据
                                    //this.list.splice(index, 1);
                                    this.getList();
                                })
                                .catch(() => {
                                    this.loading = false;
                                });
                        })
                        .catch(() => {
                            this.$message.warning("已取消");
                        });
                }
            },

            /*日期选择事件*/
            dateChange(val) {
                if (val == null) {
                    this.query.startTime = "";
                    this.query.endTime = "";
                } else {
                    this.query.startTime = val[0];
                    this.query.endTime = val[1];
                    this.query.currentPage = 1;
                }
                this.getList();
                console.log(this.query)
            },
        }, created() {
            this.getList();
        }
    }
    //跳转路由的方法
    // this.$router.push({
    //     path: "",
    //     query:{
    //         username:"张三"
    //     }
    // });
    //接受路由传递的参数
    //let query = this.$route.query;
</script>
